package Pages;


import java.io.IOException;

import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.game.Sprite;

import Const.GConfig;
import Const.IDTouch;
import Const.IDSound;
import Core.GLives;
import Core.KEY;
import Core.MRecord;
import Core.ScrollMe;
import Core.Slide;
import Core.Touch;

public class Game extends Slide {
	public boolean isFinishGame;// Hoan thanh tac ca level
	public boolean isGameOver;// Over game
	public boolean isGameWin;// Thang 1 level
	public int MAX_LEVEL = 20;// level duoc lay tu MY_MAX_LEVEL trong CMainMidlet

	private boolean isDialog = false;
	private boolean isBuying = false;
	private Image imgTool[] = new Image[4];
	private Image imgHome, imgGo, imgLight, imgBuy;
	private Image imgInfo;
	private Image imgbgBuy, imgFocusBuy;

	// InfoPage Game
	public int score;//, scoreBegin = 0;
	public int money = 1000;
	public int level = 1;
	public static int timeTick = 0;

	// pass level
	private int timePassLevel, iStepPass;
	private Image imgPassLevel, imgDay[] = null;
	private boolean isPassLevel;

	// method
	public CPlayer player;
	public ScrollMe map = null;
	
	private int arrTopScore[] = new int[GConfig.maxHightScore];
	private String arrTopScoreN[] = new String[GConfig.maxHightScore];
	private boolean isGameLoadNew = true;
	private long timeStart, timeBeginLight;
	private int time = 500, tLight = 0;
	int timeDialogStart=-1;
	private int indexItem = 0;
	public boolean isShowIGM = false;
	private int countLive = 0;
	private String strErr = null;
	private int efgap = 0;
	
	public short arrItem[] = new short[4];
	private int arrTien[] = {100, 600, 900, 200}; 
	private String arrDesc[] = {"Lưu vết bước chân.", "Chống va chạm tường.", "Mạng. Chỉ được mua 2 lần!", "Đèn pin soi đường hầm."}; 
	
	public Game(int mainState) {
		if(mainState == State.BODY_CONTINUE)
			isGameLoadNew = false;
		else
			isGameLoadNew = true;
		level = 1;
		score = 0;
		
		//GLives.isTouchable = false;
		this.setGameSize(500, 400 + GConfig.k_iPanelH, (!GLives.isTouchable ? GConfig.k_iStatusBarH : 0));
	}

	public void init() {
		KEY.resetKeys();
		score = 0;
		countLive = 0;
		time = 500;
		level = 1; // for load game //debuf
		isFinishGame = false;
		isGameOver = false;
		isGameWin = false;
		timeTick = 0;
		isPassLevel = false;
		try {
			imgInfo = Image.createImage("/info.png");
		} catch (IOException e) {
			System.out.println("[@Van] Load image background error:" + e.toString());
		}

		for(int i = 0; i < arrTopScore.length; i++){
			arrTopScoreN[i] = "";
			arrTopScore[i] = 0;
		}

		if(GLives.isTouchable) initMenuTouch();
		// Khoi tao nhung thong tin khi moi bat dau vao game
		player = new CPlayer(this);
		
		loadGame(isGameLoadNew);
		
		timeStart = System.currentTimeMillis();
		
		map = new ScrollMe(player.imgBuffer, 0);
		
		onResize();
		
		map.goTo(player.focus.getX() + player.focus.getW()/2, player.focus.getY() + player.focus.getH()/2);
		
		sound.playBackground(IDSound.BKG_MAIN, -1);
		
		for(int i = 0; i < 4; i++)
			System.out.println("arrItem[" + i + "] = " + arrItem[i]);
	}
	
	public void onResize(){
		this.setGameSize(500, 400 + GConfig.k_iPanelH, (!GLives.isTouchable ? GConfig.k_iStatusBarH : 0));
		map.setViewer(inX, inY + GConfig.k_iPanelH, inW, inH - GConfig.k_iPanelH);
	}
	
	public void destroy() {
		for(int i = 0; i < 4; i++)
			imgTool[i] = null;
		imgHome = null;
		imgGo = null;
		imgLight = null;
		imgBuy = null;
		imgInfo = null;
		imgbgBuy = null;
		imgFocusBuy = null;
		if(imgDay != null)
		for(int i = 0; i < imgDay.length; i++)
			imgDay[i] = null;
		player.imgBuffer = null;
		player.unloadPlayer();
	}
	
	public void touchDrag(int x, int y) {
		map.move(x, y);
	}
	public void touchDown(int ID, int x, int y) {
		if(ID != Touch.NOTHING || isBuying || isDialog)
			map.isActive = false;
		else
			map.moveStart(x, y);
	}
	public void touchUp(int ID, int x, int y, int dragTime, int xBegin, int yBegin) {
		map.moveFinish(ID, x, y, dragTime, xBegin, yBegin);
	}
	
	public void Click(int ID, int x, int y){
		switch(ID){
		case IDTouch.BUY:
			KEY.pressKey(KEY.LEFT_SOFTKEY);		break;
		case IDTouch.GO:
			if(isBuying) isBuying = false;
			KEY.pressKey(KEY.OK);				break;
		case IDTouch.HOME:
			KEY.pressKey(KEY.RIGHT_SOFTKEY);	break;
		case IDTouch.ITEM_LUUVET:
			if(indexItem == 0)
				ActionBuy(IDTouch.ITEM_LUUVET);
			else indexItem = 0;					break;
		case IDTouch.ITEM_CHAMTUONG:
			if(indexItem == 1)
				ActionBuy(IDTouch.ITEM_CHAMTUONG);
			else indexItem = 1;					break;
		case IDTouch.ITEM_MANG:
			if(indexItem == 2)
				ActionBuy(IDTouch.ITEM_MANG);
			else indexItem = 2;					break;
		case IDTouch.ITEM_DENPIN:
			if(indexItem == 3)
				ActionBuy(IDTouch.ITEM_DENPIN);
			else indexItem = 3;					break;
		case IDTouch.SHOW_MAP:
			player.createMapBuffer(false);
			tLight = GConfig.k_iLightTime;
			arrItem[IDTouch.ITEM_DENPIN-3]--;
			if(arrItem[IDTouch.ITEM_DENPIN-3] == 0){
				Touch.removeTouchID(IDTouch.SHOW_MAP);
			}
			break;
		case Touch.NOTHING:
			if(player.isStep){
				int xnew = x - map.getX();
				int ynew = y - map.getY();
				player.focus.setX(xnew - (player.focus.getW()>>1));
				player.focus.setY(ynew - (player.focus.getH()>>1));
				map.goTo(xnew, ynew);
			} else if (isGameWin && timePassLevel > 0){
				timePassLevel = 0;
			}
		}
	}
	
	private void showIGM(){
		isShowIGM = true;
		changeSubState(State.INBODY_MENU);
	}

	private void initBuy(){
		try {
			imgFocusBuy = Image.createImage("/focus.png");
			imgbgBuy = Image.createImage("/naphom.png");
			imgTool[0] = Image.createImage("/tool_luuvet.png");
			imgTool[1] = Image.createImage("/tool_dungtuong.png");
			imgTool[2] = Image.createImage("/tool_mang.png");
			imgTool[3] = Image.createImage("/tool_denpin.png");
			
			registerTouchBUY();
			
			efgap = imgbgBuy.getHeight();
		} catch (Exception e) {
		}
	}
	
	private void initMenuTouch(){
		try {
			imgHome = Image.createImage("/iHome.png");
			imgGo = Image.createImage("/iGo.png");
			imgLight = Image.createImage("/iLight.png");
			imgBuy = Image.createImage("/iBuy.png");
		} catch (Exception e) {
		}
	}
	
	public void initChangeLevel() {
		// Khoi tao lai nhung thong tin can thiet khi tang level
		countLive = 0;
		time = 500;
		timeStart = System.currentTimeMillis();
		isFinishGame = false;
		isGameOver = false;
		isGameWin = false;
		timeTick = 0;
		isPassLevel = false;
		int nlive = player.men.getNumLive();
		player.initialize();
		if(nlive > GConfig.k_iNumLive) player.men.setNumLive(nlive);
		map.goTo(player.focus.getX() + player.focus.getW()/2, player.focus.getY() + player.focus.getH()/2);
		registerTouch();
	}
	
	private void registerTouchBUY(){
		if(!GLives.isTouchable) return;
		for(int i = 0; i < 4; i++){
			Touch.addTouchArea(IDTouch.ITEM_LUUVET + i, inX + GConfig.k_iBuyX + GConfig.k_iBuy_kc + (imgTool[i].getWidth() + GConfig.k_iBuy_kc)*i, GLives.ScreenHeight - inY - GConfig.k_iBuyY, imgTool[i].getWidth(), imgTool[i].getHeight());
		}
	}
	
	public void registerTouch(){
		if(!GLives.isTouchable) return;
		System.out.println("-- Dang ky TOUCH");
		Touch.releaseTouchArea();
		Touch.addTouchArea(IDTouch.GO, inX + GConfig.k_iMenu_X, GLives.ScreenHeight - inY - GConfig.k_iMenu_Y - GConfig.k_iMenu_W, GConfig.k_iMenu_W, GConfig.k_iMenu_W);
		Touch.addTouchArea(IDTouch.HOME, inX + inW-GConfig.k_iMenu_W-5, inY + GConfig.k_iPanelH + 5, GConfig.k_iMenu_W, GConfig.k_iMenu_W);
		if(!player.isStep)
			Touch.addTouchArea(IDTouch.BUY, inX + GConfig.k_iMenu_X, GLives.ScreenHeight - inY - 2*GConfig.k_iMenu_Y - 2*GConfig.k_iMenu_W, GConfig.k_iMenu_W, GConfig.k_iMenu_W);
		if(arrItem[IDTouch.ITEM_DENPIN-3] > 0 && player.isStep)
			Touch.addTouchArea(IDTouch.SHOW_MAP, inX + GConfig.k_iMenu_X , GLives.ScreenHeight - inY - 2*GConfig.k_iMenu_Y - 2*GConfig.k_iMenu_W, GConfig.k_iMenu_W, GConfig.k_iMenu_W);
		if(isBuying)
			registerTouchBUY();
	}

	public void initPassLevel() {
		iStepPass = 0;
		if (imgPassLevel == null) {
			try {
				imgPassLevel = Image.createImage("/passLevel.png");
				imgDay = new Image[5];
				for(int i = 0; i < 5; i++)
					imgDay[i] = Image.createImage("/day-"+(i+1)+".png");
			} catch (IOException e) {
				System.out.println("Load imgPassLevel error: " + e.toString());
			}
		}
	}

	public void paint(Graphics g) {
		g.setColor(0x000000);
		g.fillRect(0, 0, GLives.ScreenWidth, GLives.ScreenHeight);
		player.paint(g);

		g.setClip(inX, inY, inW, inH);
		
		if (isBuying) paintBuy(g);
		paintInfo(g);

		resetClip(g);
		
		paintSoftMenu(g);

		if (isDialog)
			paintDialog(g);
		
		// pass level
		if (isGameWin && timePassLevel > 0)
			paintPassLevel(g);
	}

	private void paintBuy(Graphics g){
		int x = inX + GConfig.k_iBuyX;
		int y = inY + inH - GConfig.k_iBuyY + efgap;
		if(!GLives.isTouchable){
			x = (GLives.ScreenWidth - imgbgBuy.getWidth())>>1;
			y = y - GConfig.k_iStatusBarH;
		}
		g.drawRegion(imgbgBuy, 0, 0, imgbgBuy.getWidth(), imgbgBuy.getHeight(), Sprite.TRANS_MIRROR_ROT180, 0, inY + inH + efgap, Graphics.BOTTOM|Graphics.LEFT);
		drawStringBold(g, "Bạn có $" + money, x + (GConfig.k_iItem_W + GConfig.k_iBuy_kc)*2, y - 22, 2, 0x0);
		g.drawImage(imgFocusBuy, x + GConfig.k_iBuy_kc + (imgTool[indexItem].getWidth() + GConfig.k_iBuy_kc)*indexItem + (imgTool[indexItem].getWidth()>>1), y + (imgTool[indexItem].getHeight()>>1), Graphics.HCENTER|Graphics.VCENTER);
		for(int i = 0; i < 4; i++){
			g.drawImage(imgTool[i], x + GConfig.k_iBuy_kc + (imgTool[i].getWidth() + GConfig.k_iBuy_kc)*i, y, 0);
			drawString(g, "" + arrTien[i], x + GConfig.k_iBuy_kc + (imgTool[i].getWidth() + GConfig.k_iBuy_kc)*i + (GConfig.k_iItem_W>>1), y + GConfig.k_iItem_W + 2, 2, 0x999999);
		}
		drawString(g, arrDesc[indexItem], x + GConfig.k_iBuy_kc, y + GConfig.k_iItem_W + 20, 0, 0x00FFAA);
	}
	
	void paintSoftMenu(Graphics g){
		if(GLives.isTouchable){ // phone touch
			if(arrItem[IDTouch.ITEM_DENPIN-3] > 0 && player.isStep)
				Touch.drawImage(g, IDTouch.SHOW_MAP, imgLight);
			Touch.drawImage(g, IDTouch.HOME, imgHome);
			Touch.drawImage(g, IDTouch.GO, imgGo);
			Touch.drawImage(g, IDTouch.BUY, imgBuy);
		} else if (!isShowIGM) { // phone key
			if(!isGameWin){
				if(!player.isStep){
					drawStringBold(g, isBuying ? "Đóng" : "Mua", 5, GLives.ScreenHeight - 18, 0, 0xFFAA11);
					drawStringBold(g, isBuying ? "Mua" : "Bắt đầu", GLives.ScreenWidth>>1, GLives.ScreenHeight - 18, 2, 0xFFAA11);
				}
				else{
					if(arrItem[IDTouch.ITEM_DENPIN-3] > 0)
						drawStringBold(g, "Bật đèn", 5, GLives.ScreenHeight - 18, 0, 0xFFAA11);	
					drawStringBold(g, isBuying ? "Mua" : "Đi", GLives.ScreenWidth>>1, GLives.ScreenHeight - 18, 2, 0xFFAA11);
				}
				
				drawStringBold(g, "Menu", GLives.ScreenWidth - 5, GLives.ScreenHeight - 18, 1, 0xFFAA11);
			}
		}
	}
	
	public void paintInfo(Graphics g) {
		g.drawRegion(imgInfo, 0, 0, 18, 19, 0, inX + 5, inY + (GConfig.k_iPanelH>>1), Graphics.LEFT|Graphics.VCENTER);
		drawString(g, (level<10? "0" : "") + level, inX + 20, inY + GConfig.k_iPanelTextY, 0, 0x00FFAA);
		g.drawRegion(imgInfo, 18, 0, 18, 19, 0, inX + 40, inY + (GConfig.k_iPanelH>>1), Graphics.LEFT|Graphics.VCENTER);
		drawString(g, ""+time, inX + 56, inY + GConfig.k_iPanelTextY, 0, 0xFF00AA);
		
		g.drawRegion(imgInfo, 36, 0, 18, 19, 0, inX + inW - 132, inY + (GConfig.k_iPanelH>>1), Graphics.RIGHT|Graphics.VCENTER);
		drawString(g, (arrItem[IDTouch.ITEM_LUUVET-3]<10? "0" : "") + arrItem[IDTouch.ITEM_LUUVET-3], inX + inW - 134, inY + GConfig.k_iPanelTextY, 0, 0x00FFAA);
		
		g.drawRegion(imgInfo, 54, 0, 18, 19, 0, inX + inW - 98, inY + (GConfig.k_iPanelH>>1), Graphics.RIGHT|Graphics.VCENTER);
		drawString(g, (arrItem[IDTouch.ITEM_CHAMTUONG-3]<10? "0" : "")+arrItem[IDTouch.ITEM_CHAMTUONG-3], inX + inW - 96, inY + GConfig.k_iPanelTextY, 0, 0x00FFAA);
		
		g.drawRegion(imgInfo, 72, 0, 18, 19, 0, inX + inW - 58, inY + (GConfig.k_iPanelH>>1), Graphics.RIGHT|Graphics.VCENTER);
		drawString(g, (arrItem[IDTouch.ITEM_DENPIN-3]<10? "0" : "")+arrItem[IDTouch.ITEM_DENPIN-3], inX + inW - 56, inY + GConfig.k_iPanelTextY, 0, 0x00FFAA);
		
		g.drawRegion(imgInfo, 90, 0, 18, 19, 0, inX + inW - 20, inY + (GConfig.k_iPanelH>>1), Graphics.RIGHT|Graphics.VCENTER);
		drawString(g, (player.men.getNumLive()<10? "0" : "")+player.men.getNumLive(), inX + inW - 18, inY + GConfig.k_iPanelTextY, 0, 0xFFAA11);
	}

	private void paintDialog(Graphics g){
		if(isDialog){
			g.setColor(0x001100);
			g.fillRect((GLives.ScreenWidth - GConfig.k_iDialog_W) >> 1, (GLives.ScreenHeight - GConfig.k_iDialog_H) >> 1, GConfig.k_iDialog_W, GConfig.k_iDialog_H);
			g.setColor(0xFFAA99);
			g.drawRect((GLives.ScreenWidth - GConfig.k_iDialog_W) >> 1, (GLives.ScreenHeight - GConfig.k_iDialog_H) >> 1, GConfig.k_iDialog_W, GConfig.k_iDialog_H);
			
			if(timeTick % 15 > 3)
				drawString(g, strErr, GLives.ScreenWidth >> 1, (GLives.ScreenHeight >> 1) - 10, 2, 0xFFAA11);
		}
	}
	
	private void paintPassLevel(Graphics g) {
		if (imgPassLevel == null)
			return;
		
		g.drawImage(imgDay[iStepPass%5], inX + iStepPass + 7, (GLives.ScreenHeight>>1) + 35, Graphics.RIGHT | Graphics.BOTTOM);
		g.drawImage(imgPassLevel, inX + iStepPass, (GLives.ScreenHeight>>1) + 40, Graphics.LEFT | Graphics.BOTTOM);
	}

	private void showDialog(String messenger){
		strErr = messenger;
		isDialog = true;
		timeDialogStart = timeTick;
	}
	
	private void ActionBuy(int indexItem){
		
		if(indexItem > 0 && money < arrTien[this.indexItem]){
			showDialog("Bạn không có đủ tiền để mua.");
			isBuying = false;
			registerTouch();
			return;
		}
		
		switch(indexItem){
		case IDTouch.ITEM_LUUVET:
			player.addStep(GConfig.k_iAddStep);
			break;
		case IDTouch.ITEM_CHAMTUONG:
			// following
			break;
		case IDTouch.ITEM_MANG:
			countLive++;
			if(countLive > 2)
				showDialog("Bạn chỉ mua được 2 mạng.");
			else
				player.men.setNumLive(player.men.getNumLive() + 1);
			break;
		case IDTouch.ITEM_DENPIN:
			// following + registerTouch
			break;
		}
		
		if(indexItem > 0){
			arrItem[this.indexItem]++;
			money -= arrTien[this.indexItem];
		}
		
		isBuying = false;
		registerTouch();
	}
	
	public void C_H_E_A_T(){
		// buy
		if(isBuying){
			if(GLives.isTouchable){
				if(Touch.holdTime > 0 && Touch.xDown < 50 && Touch.xUp > GLives.ScreenWidth - 50 && Touch.yDown < 50 && Touch.yUp < 50){
					money += 1000;
					Touch.resetPos();
				}
			} else {
				if(KEY.isPressed(KEY.STAR) && KEY.isPressed(KEY.POUND)){
					money += 1000;
					KEY.resetKey(KEY.STAR);
					KEY.resetKey(KEY.POUND);
				}
			}
		}
		// forward Stage
		if(!isBuying && !player.isStep){
			if(GLives.isTouchable){
				if(Touch.holdTime > 0 && Touch.holdTime < 500 && Touch.xDown < 100 && Touch.xUp > GLives.ScreenWidth - 100 && Touch.yDown < inY + 50 && Touch.yUp < 50 && Touch.yDown > inY){
					isGameWin = true;
					Touch.resetPos();
				}
			} else {
				if(KEY.LoopCount(KEY.STAR) > 30 && KEY.LoopCount(KEY.POUND) > 10 && KEY.LoopCount(KEY.POUND) < 15){
					isGameWin = true;
					KEY.resetKey(KEY.STAR);
					KEY.resetKey(KEY.POUND);
				}
			}
		}
	}
	
	public void update() {
		if(GConfig.hasCheat) C_H_E_A_T();
		map.update();
		CPlayer.s_iMapX = map.getX();
		CPlayer.s_iMapY = map.getY();
		updateTime();
		// Cac ham update
		if(efgap > 0) {efgap -= (imgbgBuy.getHeight() - efgap +4)>>2; if(efgap < 0) efgap = 0;}
		
		if(!(isGameOver || isFinishGame || isGameWin))
		if (KEY.isPressed(KEY.LEFT_SOFTKEY)) {
			if(!player.isStep){
				if(isBuying) // close Dialog BUY
					ActionBuy(Touch.NOTHING);
				else { // open Dialog BUY
					isBuying = true;
					initBuy();
				}
			} else if(arrItem[IDTouch.ITEM_DENPIN-3] > 0){
				Click(IDTouch.SHOW_MAP, 0, 0);
			}
			KEY.resetKeys();
		} else
		if (KEY.isPressed(KEY.RIGHT_SOFTKEY)) {// IGM
			//if(!isBuying)
			showIGM();
			KEY.resetKeys();
		} else
		if (KEY.isPressed(KEY.OK)) {
			if(isBuying){
				ActionBuy(indexItem + IDTouch.ITEM_LUUVET);
			} else
			if (!player.isStep){
				player.isStep = true;
				registerTouch();
			}
			else {
				player.men.setPosition(player.focus.getX(), player.focus.getY());
				map.goTo(player.men.getX() + player.men.getW()/2, player.men.getY() + player.men.getH()/2);
				score++;
			}
			KEY.resetKeys();
		} else
		if (!isGameWin) {
			player.update();
			
			if (KEY.isPressed(KEY.RIGHT)) {
				if(isBuying) { indexItem = (indexItem >= 3 ? 0 : indexItem+1); KEY.resetKey(KEY.RIGHT);}
				else if(!player.isStep) map.scrollRight(); else map.goTo(player.focus.getX() + player.focus.getW()/2, player.focus.getY() + player.focus.getH()/2);
			} else if (KEY.isPressed(KEY.LEFT)) {
				if(isBuying) { indexItem = (indexItem <= 0 ? 3 : indexItem-1); KEY.resetKey(KEY.LEFT);}
				else if(!player.isStep) map.scrollLeft(); else map.goTo(player.focus.getX() + player.focus.getW()/2, player.focus.getY() + player.focus.getH()/2);
			} else if (KEY.isPressed(KEY.DOWN)) {
				if(!isBuying) if(!player.isStep) map.scrollDown(); else map.goTo(player.focus.getX() + player.focus.getW()/2, player.focus.getY() + player.focus.getH()/2);
			} else if (KEY.isPressed(KEY.UP)) {
				if(!isBuying) if(!player.isStep) map.scrollUp(); else map.goTo(player.focus.getX() + player.focus.getW()/2, player.focus.getY() + player.focus.getH()/2);
			}
		}
		
		if ((isGameOver || isFinishGame)) {// Khi game over hoac hoan thanh game xu ly o day
			if(isFinishGame)
				money += time;
			saveGame();
			changeState(State.THEEND);
			if(isGameOver)
				((EndGame)GLives.ins.currSlide).setContent(0, money);
			else if (isFinishGame)
				((EndGame)GLives.ins.currSlide).setContent(1, money);
			
			//uploadAllImageInPlay();
			KEY.resetKeys();
		} else if (isGameWin) {// Khi thang 1 level xu ly o day
			if (KEY.isPressed(KEY.OK) && timePassLevel > 0){
				timePassLevel = 0;
			}
			if (level == MAX_LEVEL) {
				isFinishGame = true;
			} else if (!isPassLevel) {
				isPassLevel = true;
				timePassLevel = GConfig.k_iTimePassLevel;
				initPassLevel();
			} else if (timePassLevel == 0) {
				money += time;
				IncreaseLevelGame();
				isGameWin = false;
				unloadPassLevel();
				isPassLevel = false;
			}
			KEY.resetKeys();
		}
	}

	public void updateTime() {
		long t = System.currentTimeMillis();
		if(player.isStep && time > 0 && t - timeStart > 1000 && !isPassLevel){
			time--;
			timeStart = t;
		}
		
		if (tLight > 0 && t - timeBeginLight > 1000){
			tLight--;
			if(tLight == 0) player.createMapBuffer(true);
			timeBeginLight = t;
		}
		
		if (isPassLevel) {
			iStepPass+=3;
			if(iStepPass >= inW + 10){
				//isPassLevel = false;
				timePassLevel = 0;
			}
//			if (timePassLevel == 0)
//				isPassLevel = false;
//			else
//				timePassLevel--;
		}
		
		if (timeTick > 100000)
			timeTick = 0;
		if (timeTick % 10 == 0) {
			if (player.isStep && player.iTimeHideMap >= 0 && !isGameWin) {
				player.createMapBuffer(true);
				player.iTimeHideMap--;
			}
			if(isDialog){
				if(timeTick - timeDialogStart > 25 || timeTick < timeDialogStart)
					isDialog = false;
			}
		}
		timeTick++;
	}

	public void unloadPassLevel() {
		imgPassLevel = null;
	}

	public void IncreaseLevelGame() {
		// Qua level
		level++;
		if (level > MAX_LEVEL) {
			isFinishGame = true;
		} else {
			initChangeLevel();
		}
	}
	
	public void updateTopScore(int newScore, String gamer){
		for(int i = 0; i < arrTopScore.length; i++){
			if(newScore > arrTopScore[i]){
				for(int j = arrTopScore.length-1; j > i; j--){
					arrTopScore[j] = arrTopScore[j-1];
					arrTopScoreN[j] = arrTopScoreN[j-1];
				}
				arrTopScore[i] = newScore;
				arrTopScoreN[i] = gamer;
				return;
			}
		}
	}
	
	public void saveScore(){
		MRecord r = GLives.ins.record;
		if(r.openRecStore(true)){
			r.seek(1, MRecord.k_P_START);
			for(int i = 0; i < arrTopScore.length; i++){
				r.writeString(arrTopScoreN[i]);
				r.writeInt(arrTopScore[i]);
			}
		r.saveRecordStore();
		}
	}
	
	public void saveGame(){
		MRecord r = GLives.ins.record;
		if(r.openRecStore(true)){
			boolean isGameFinish = (isFinishGame || isGameOver || (level == 1 && !player.isStep));
			System.out.println("Save: Game finish: "+isGameFinish);
			r.writeBoolean(isGameFinish); 
			
			System.out.println("--------B---------");
			int gap = 0;
			for(int i = 0; i < arrTopScore.length; i++)
				gap += 4 + 2 + arrTopScoreN[i].length();
			System.out.println("--------A---");
			r.seek(gap, MRecord.k_P_CURRUNT);

			r.writeInt(isGameFinish ? 1 : level);
			if(!isGameFinish){
				//r.writeInt(score);
				r.writeInt(money);
				
				r.writeInt(time);
				r.writeShort(arrItem[IDTouch.ITEM_LUUVET-3]);
				r.writeShort(arrItem[IDTouch.ITEM_CHAMTUONG-3]);
				r.writeShort(arrItem[IDTouch.ITEM_DENPIN-3]);
				r.writeInt(player.men.getNumLive());
				
				r.writeInt(player.men.getX());
				r.writeInt(player.men.getY());
				
				r.writeBoolean(player.isStep);
				r.writeBoolean(player.hasBox);
			}

			r.saveRecordStore();
		}
	}
	public void loadGame(boolean isloadnew){
		MRecord r = GLives.ins.record;
		if(r.openRecStore(false)){
			boolean isGameFinish = r.readBoolean();
			for(int i = 0; i < arrTopScore.length; i++){
				arrTopScoreN[i] = r.readString();
				arrTopScore[i] = r.readInt();
			}
			
			if(isloadnew){
				level = 1;
				r.seek(0, MRecord.k_P_START);
				r.writeBoolean(true);
				r.saveRecordStore();
			}
			else
				level = r.readInt();
			
			player.initialize();
			
			if(!isGameFinish && !isloadnew){
				//score = r.readInt();
				money = r.readInt();
				
				time = r.readInt();
				arrItem[IDTouch.ITEM_LUUVET-3] = r.readShort();
				player.addStep(arrItem[IDTouch.ITEM_LUUVET-3]*GConfig.k_iAddStep + (level-1)*GConfig.k_inStep);
				arrItem[IDTouch.ITEM_CHAMTUONG-3] = r.readShort();
				arrItem[IDTouch.ITEM_DENPIN-3] = r.readShort();
				player.men.setNumLive(r.readInt());
				
				player.men.setX(r.readInt());
				player.men.setY(r.readInt());
				player.focus.setX(player.men.getX());
				player.focus.setY(player.men.getY());
				
				player.isStep = r.readBoolean();
				if(player.isStep)
					player.iTimeHideMap = GConfig.k_iTimeHideMap + 5;
				player.hasBox = r.readBoolean();
				player.men.setHasBox(player.hasBox);
			}
		} else
			player.initialize();
	}
	
}
